# When an error happens in a rails created form field, it normally gets
# surrounded by a <div> tag, but this changes it to a <span>.
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag|
  "<span class='field_error'>#{html_tag}</span>"
end

# Don't colorize logging, because it creates a mess in windows prompts.
# Change this to true, if on a unix based shell
ActiveRecord::Base.colorize_logging = false

class ApplicationController < ActionController::Base
  helper :all
  helper_method :current_user, :logged_in?, :redirect_back_or_default
  filter_parameter_logging :password, :password_confirmation
  protect_from_forgery
  
  protected
  
  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end
  
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end
  
  def logged_in?
    current_user
  end
  
  def login_required
    unless logged_in?
      flash[:notice] = 'You must be logged in view this resource'
      store_target_location
      redirect_to login_url
    end
  end
  
  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end
  
  private
  
  def store_target_location
    session[:return_to] = request.request_uri
  end
end
